//
//  WringViewControlelr.m
//  LineByLine
//
//  Created by 병철 김 on 11. 10. 25..
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "WritingViewController.h"
#import "CommonDefine.h"
#import "WritingViewCell.h"
#import "CoreDataManager.h"


@implementation WritingViewController 


#pragma mark - init/dealloc

- (void)loadView {
    [super loadView];
    NSNumber *page = [[StudyManager sharedStudyManager] pageOfBook:book step:[NSNumber numberWithInt:4]];
    [self setCurPage:[page intValue]];
    
    writingView= [[Step4WritingView alloc] initWithFrame:CGRectMake(0, 0, kContentWidth, kContentHeight2)];
    [writingView setCurPage:[page intValue]];
    [writingView setDataSource:self];
    [writingView setViewDelegate:self];
    [writingView configView];
    [self.view addSubview:writingView];
    [writingView release];
    
    [[StudyManager sharedStudyManager] startTimerWith:&curPage];
}

- (NSNumber*) step {
    if (!step) {
        step = [[NSNumber numberWithInt:4] retain];
    }
    return step;
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"%@", [book valueForKey:@"lines"]);
    return [[book valueForKey:@"lines"] intValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"WritingViewCell";
    WritingViewCell *cell = (WritingViewCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[WritingViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
        CGRect frame = cell.frame;
        frame.size.height = kContentHeight;
        [cell setFrame:frame];
        [cell setWordsViewDelegate:self];
    }
    
    id sentence = [[CoreDataManager sharedCoreDataManager] selectOneFrom:@"Sentence" where:@"book=%@ and sid=%@", book, [NSNumber numberWithInt:(indexPath.row + 1)], nil];
    [cell setSentence:sentence];
    [cell configView];
    return cell;
}

#pragma mark - StepViewController Dynamic Method
- (StepView*) stepView {
    return writingView;
}

#pragma mark - StepViewDelegate
- (void)didChangePage:(NSInteger)page {
    [super didChangePage:page];
    [[StudyManager sharedStudyManager] startTimerWith:&curPage];
}

#pragma mark - WordsViewDelegate
- (NSTimeInterval) didFinishSentence:(id) sentence {
    NSTimeInterval duration = [[StudyManager sharedStudyManager] stopTimerWith:&curPage];
    return duration;
}
@end
